<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="40%"
    append-to-body
    destroy-on-close>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="接口代码" prop="ifCode">
            <el-input v-model="form.ifCode" placeholder="请输入" :disabled="form.ifCode !== undefined && isAdd === false " />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="接口名称" prop="ifName">
            <el-input v-model="form.ifName" placeholder="请输入" />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">
          <el-form-item label="是否支持普通商户模式" prop="isMchMode">
            <el-radio-group v-model="form.isMchMode">
              <el-radio :label="0">不支持</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否支持服务商子商户模式" prop="isIsvMode">
            <el-radio-group v-model="form.isIsvMode">
              <el-radio :label="0">不支持</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>-->
<!--        <el-col :span="24">
          <el-form-item label="支付参数配置页面类型" prop="configPageType">
            <el-radio-group v-model="form.configPageType">
              <el-radio :label="2">自定义页面</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="状态" prop="state">
            <el-radio-group v-model="form.state">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支持的支付方式" prop="checkedList">
            <el-checkbox-group v-model="checkedList" @change="onWayCodesChange">
              <el-checkbox
                v-for="item in wayCodesOptions"
                :key="item.value"
                :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updatePayIfDefine, addPayIfDefine, getPayWayCodes } from '@/api/pay/payconfig/payIfDefine/payIfDefine'
import { getToken } from "@/utils/auth"
import FileUpload from '@/components/FileUpload'
import ImagePreview from '@/components/ImagePreview'

export default {
  name: 'PayInterfaceForm',
  components: {
    FileUpload,
    ImagePreview
  },
  data() {
    const validateWayCodes = (rule, value, callback) => { // 支付方式 验证器
      if (this.checkedList.length <= 0) {
        callback(new Error('请选择支付方式'))
      }
      callback()
    }
    return {
      // 遮罩层
      loading: false,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      visible: false,
      // 表单参数
      form: {
        ifCode: undefined,
        ifName: undefined,
        isMchMode: 0,
        isIsvMode: 0,
        state: 1,
        configPageType: 2, // 修改: 默认值改为 2（自定义页面）
        icon: undefined,
        bgColor: undefined,
        remark: undefined,
        wayCodes: []
      },
      isAdd: true, // 是否为新增操作
      wayCodesOptions: [], // 支付方式多选框选项列表
      checkedList: [], // 选中的数据
      // 添加表单验证规则
      rules: {
        ifCode: [{ required: true, message: '请输入接口代码', trigger: 'blur' }],
        ifName: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
        checkedList: [{ validator: validateWayCodes, trigger: 'change' }]
      },
      previewVisible: false,
      previewImage: '',
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getWayCodesList()
          if (this.form.wayCodes && Array.isArray(this.form.wayCodes)) {
            this.checkedList = this.form.wayCodes.map(item => typeof item === 'object' ? item.wayCode : item)
          }
        }
      }
    }
  },
  methods: {
    // 重命名并重构支付方式列表获取方法
    async getWayCodesList() {
      try {
        this.loading = true
        const response = await getPayWayCodes()

        if (!response) {
          throw new Error('获取支付方式列表失败：响应为空')
        }

        if (response.code === 200 && response.rows) {
          this.wayCodesOptions = (response.rows || []).map(item => ({
            label: item.wayName,
            value: item.wayCode
          }))
        } else {
          throw new Error(response.msg || '获取支付方式列表失败')
        }
      } catch (error) {
        console.error('获取支付方式列表错误:', error)
        this.$modal.msgError(error.message || '获取支付方式列表失败')
        this.wayCodesOptions = []
      } finally {
        this.loading = false
      }
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset()
      this.isAdd = true
      this.visible = true
      this.title = '新增支付接口'
      try {
        await this.getWayCodesList()
      } catch (error) {
        console.error('新增操作获取支付方式失败:', error)
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const submitData = {
            ...this.form,
            wayCodes: this.checkedList.map(code => ({ wayCode: code })) // 将每个code转换为对象数组
          }

          const submitOperation = this.isAdd ? addPayIfDefine : updatePayIfDefine

          submitOperation(submitData).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess(this.isAdd ? "新增成功" : "修改成功")
              this.visible = false
              this.$emit('refreshList') // 触发父组件的刷新方法
              this.$emit("ok")
            } else {
              this.$modal.msgError(response.msg || (this.isAdd ? "新增失败" : "修改失败"))
            }
          }).catch(error => {
            console.error('操作失败:', error)
            this.$modal.msgError(this.isAdd ? "新增失败" : "修改失败")
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.visible = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        ifCode: undefined,
        ifName: undefined,
        isMchMode: 0,
        isIsvMode: 0,
        state: 1,
        configPageType: 1,
        icon: undefined,
        bgColor: undefined,
        remark: undefined,
        wayCodes: []
      }
      this.checkedList = [],
      this.form.wayCodes = [],
      this.isAdd=true,
      this.resetForm("form")
    },
    /** 上传图片成功回调 */
    handleIconSuccess(response) {
      if (response.code === 200) {
        // 根据实际返回数据结构调整
        this.form.icon = response.data ? response.data.url : response.url;
        this.$message.success("上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
      }
    },
    /** 图片预览 */
    handlePreview(file) {
      this.previewImage = file.url;
      this.previewVisible = true;
    },
    onWayCodesChange(checkedValues) {
      this.checkedList = checkedValues
      this.form.wayCodes = checkedValues
    }
  }
}
</script>

<style lang="scss" scoped>
.image-preview {
  margin-bottom: 10px;

  .el-image {
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    &:hover {
      border-color: #409EFF;
    }
  }
}

.image-upload {
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }
  }
  .el-upload__tip {
    font-size: 12px;
    color: #909399;
    margin-top: 7px;
  }
}
</style>
